﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Bzure.Security.Permissions
{
    public interface IAuthentication
    {
        bool Authentication(IDroit DroitResource);
    }
    //public delegate void PermissionFailHandler(IAuthentication UserPermission, PermissionEventArgs e);
    public class UserPermission : DroitCollection, IAuthentication
    {
        public DateTime TokenLoadTime { get; private set; }
        public string UserName { get; private set; }
        public string UserID { get; private set; }
        public UserPermission(string UserID, string username)
        {
            this.UserID =UserID ;
            this.UserName = username;
            InitPermission(false);
        }
        public void InitPermission(bool NeedInit)
        {
            ClearDroit();
            if (NeedInit)
            {
                RolePool.InitTreamRolePool();
                RolePool.InitTreeRolePool();
            }
            _securityTree = RolePool.GetTreeRolesByUser(this.UserID);
            _roleList = RolePool.GetTeamRolesByUser(this.UserID);
            //calculate all droits
            ColligateDroits();
            TokenLoadTime = DateTime.Now;
        }
        private IList<TeamRole> _roleList;
        /// <summary>
        /// Thread owner's security role list
        /// </summary>
        public IEnumerable<TeamRole> TeamRoles
        {
            get { return _roleList; }
        }
        private TreeRole _securityTree;
        /// <summary>
        /// Thread owner's security catalog position
        /// </summary>
        public TreeRole TreeRole
        {
            get { return _securityTree; }
        }
        private void ColligateDroits()
        {
            if (this._securityTree != null)
                this.AddDroit(this._securityTree.ColligateDroits());
            foreach (TeamRole role in this._roleList)
                this.AddDroit(role.DriotCollection);
        }

        #region implement IUsrePermission


        public virtual bool Authentication(IDroit Droit)
        {
            if (this.TokenLoadTime < Actor.Public.GetLastPermissionChangeTime())
                InitPermission(true);
            IDroit dt = this[Droit.Guid.ToString()];
            return dt == null ? false : Droit.IsSubsetOf(dt);
        }
        #endregion
    }

}
